/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kiff.interceptor;

import java.util.Map;

import kiff.entity.User;
import kiff.util.SessionConstants;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * User Interceptor injects a user into the action if it exists in the session.
 * @author Adam
 * @version $Id$
 * 
 * Created on Nov 22, 2008 at 10:01:14 PM 
 */
public class UserInterceptor implements Interceptor {
	/**
	 * Serial Version UID.
	 */
	private static final long serialVersionUID = -451550468171754518L;

	/**
	 * {@inheritDoc}
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
	 */
	public void destroy() { }

	/**
	 * {@inheritDoc}
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#init()
	 */
	public void init() { }

	/**
	 * Sets the user if one exists in the session.
	 * {@inheritDoc}
	 * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@SuppressWarnings("unchecked")
	public String intercept(final ActionInvocation actionInvocation) throws Exception {
		Action action = (Action) actionInvocation.getAction();
		if (action instanceof UserAware) {
			Map session = actionInvocation.getInvocationContext().getSession();
			User user = (User) session.get(SessionConstants.USER_SESSION);
			((UserAware) action).setUser(user);
		}
		return actionInvocation.invoke();
	}
}
